package com.efounder.presenter;

import android.content.DialogInterface;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.activity.MallSelectionPayNoAliWxActivity;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallTreasureGoodsInfoBean;
import com.efounder.bean.MallTreasurePayInfoListBean;
import com.efounder.bean.MallTreasurePayOrderInfoBean;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.util.DialogUtil;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.MallRequestUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.efounder.mvp.base.BasePresenterImpl;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.EthTokenTransactionManager;
import com.pansoft.openplanet.util.TreasureTransferUtils;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.ORDER_SNATCH_PAY_URL;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2018/11/5 17:11
 * @desc : 商品夺宝的选择支付界面  无阿里和微信支付
 * @version: 1.0
 */
public class MallSelectionPayNoAliWxPresenter extends BasePresenterImpl<MallSelectionPayNoAliWxActivity> {


    public MallSelectionPayNoAliWxPresenter(MallSelectionPayNoAliWxActivity view) {
        super(view);
    }

    /**
     * 请求订单详情接口
     *
     * @param userID  手机号
     * @param orderId 订单编号
     */
    public void getOrderDetailsData(String userID, String orderId) {
        LoadingDataUtilBlack.show(mContext,mContext.getString(R.string.dialog_title_progress_hint));
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("orderBh", orderId);
//        /pay/snatchBeforePay
        MallRequestUtil.getRequest(TAG, ORDER_SNATCH_PAY_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                if (view != null) {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    try {
                        MallTreasurePayOrderInfoBean mallTreasurePayOrderInfoBean = gson.fromJson(response, MallTreasurePayOrderInfoBean.class);
                        if(mallTreasurePayOrderInfoBean!=null){
                            if(mallTreasurePayOrderInfoBean.getResult().equals(MallRequestUtil.SUCCESS)){
                                getDataMultiple(mallTreasurePayOrderInfoBean);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
            }
        });
    }

    /**
     * 选择支付加载列表数据
     *
     * @return 数据
     */
    public void getDataMultiple(final MallTreasurePayOrderInfoBean mallTreasurePayOrderInfoBean) {

        //http://treasure.openserver.cn/osp-treasure/winTreasure/getBalanceByAccountAddress?
        // accountAddress=0x29f7220c6f4eb0d40a2dc40b67787e7f7e51053a&goodsId=001161350000028&quantity1=1&quantity2=0
        HashMap<String,String> map = new HashMap<>();
        map.put("accountAddress",payAddress);
        map.put("goodsId",mallTreasurePayOrderInfoBean.getOrder().getItems().get(0).getGood().getGoodId());
        map.put("quantity1",mallTreasurePayOrderInfoBean.getOrder().getGoodCount()+"");
        map.put("quantity2","0");
        MallRequestUtil.getRequest(TAG, MallRequestUtil.MALL_TREASURE_SELECT_PAY_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    if(view!=null){
                        Gson gson = new GsonBuilder().serializeNulls().create();
                        MallTreasurePayInfoListBean mallTreasurePayInfoListBean = gson.fromJson(response,MallTreasurePayInfoListBean.class);
                        if(mallTreasurePayInfoListBean!=null){
                            if(mallTreasurePayInfoListBean.getCode() == 0){
                                List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans = new ArrayList<>();
                                List<MallTreasurePayInfoListBean.DataBean.PaymentInfoBean.TokensBean> tokensBeans = mallTreasurePayInfoListBean.getData().getPaymentInfo().getTokens();
                                for(int i = 0;i<tokensBeans.size();i++){
                                    MallTreasurePayInfoListBean.DataBean.PaymentInfoBean.TokensBean tokensBean = tokensBeans.get(i);
                                    if(tokensBean!=null&&!tokensBean.getTokenFullName().equals("")){
                                        MallSelectionPayMultipleBean.SelectionPay selectionPay = new MallSelectionPayMultipleBean.SelectionPay();
                                        selectionPay.setPay(true);
                                        selectionPay.setTitle(tokensBean.getTokenName());
                                        selectionPay.setTokenIcon(tokensBean.getTokenIcon());
                                        selectionPay.setSurplusNum(tokensBean.getBalance());
                                        selectionPay.setRmbValue(mallTreasurePayInfoListBean.getData().getPaymentInfo().getPaymentStableCoin());
                                        selectionPay.setTokenAmount(mallTreasurePayInfoListBean.getData().getPaymentInfo().getPaymentStableCoin());
                                        selectionPay.setTokenTypeId(tokensBean.getTokenID());
                                        mallSelectionPayMultipleBeans.add(new MallSelectionPayMultipleBean(MallSelectionPayMultipleBean.PAY_WAY_ITEM,tokensBean.getTokenID(),selectionPay));
                                    }
                                }
                                view.getDataSuccess(mallTreasurePayOrderInfoBean,mallSelectionPayMultipleBeans);
                            }
                        }

                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    /**
     * adapter item中点击事件的逻辑处理
     *
     * @param adapter                   适配器
     * @param selectionPayMultipleBeans 实体类
     * @param position                  点击位置
     */
    public void onAdapterItemClick(BaseQuickAdapter adapter, List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , int position) {
        MallSelectionPayMultipleBean selectionPayMultipleBean = selectionPayMultipleBeans.get(position);
        //根据判断显示隐藏check图片
        //当前item是否能支付，可以支付继续向下走
        if (selectionPayMultipleBean.getSelectionPay().isPay()) {
            //循环列表
            for (int i = 0; i < selectionPayMultipleBeans.size(); i++) {
                //选择两个
//                if (i == position) {
//                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
//                    } else {
//                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
//                    }
//                } else if (adapter.getItemViewType(i) == selectionPayMultipleBean.getItemType()) {
//                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
//                }
//                //  选择一个
                //如果循环到当前点击位置，根据当前的选择状态设置，如果不是全部设置为false
                if (i == position) {
                    if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(false);
                    } else {
                        selectionPayMultipleBean.getSelectionPay().setSelectPayWay(true);
                    }
                } else {
                    selectionPayMultipleBeans.get(i).getSelectionPay().setSelectPayWay(false);
                }

            }
            adapter.notifyDataSetChanged();
        }
    }


    /**
     * 支付订单
     *
     */
    public void pay(String orderNumber,String goodsId,String contractAddress,String gasPrice1,String amount,String quantity1) {

        if (orderNumber == null) {
            ToastUtils.showShort(mContext.getString(R.string.mall_selection_pay_order_hint));
            return;
        }
        startTreasureTransfer(orderNumber,goodsId,contractAddress,gasPrice1,amount,quantity1);

    }



    @Override
    public void detachView() {
        view.dismissProgress();
        super.detachView();
        EFHttpRequest.cancelRequest(TAG);
        //关闭交易
        TreasureTransferUtils.getInstance().closeTransaction();

    }



    /**
     * 加载各个积分数据抵扣的方法
     * @param selectionPayMultipleBeans
     * @param ordersTotalPrice
     * @param balanceData
     * @param type
     */
    public void loadBalanceData(List<MallSelectionPayMultipleBean> selectionPayMultipleBeans
            , double ordersTotalPrice, String balanceData, String type
            ,MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter) {
        //循环列表获取对应的积分
        for (MallSelectionPayMultipleBean selectionPayMultipleBean : selectionPayMultipleBeans) {

//            if (selectionPayMultipleBean.getPayType().equals(type)) {

                String tokenAmount = selectionPayMultipleBean.getSelectionPay().getTokenAmount() + "";
                balanceData = selectionPayMultipleBean.getSelectionPay().getSurplusNum();
                //判断当前积分数量和商品价格
                if (Double.valueOf(balanceData) >= Double.valueOf(tokenAmount)) {
                    //如果积分大于价格  显示抵扣信息  否则显示余额不足，不能支付
                    String rmbValue;
                    selectionPayMultipleBean.getSelectionPay().setPay(true);
//                    rmbValue = selectionPayMultipleBean.getSelectionPay().getRmbValue() + "";
//                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(tokenAmount
//                            + mContext.getString(R.string.mall_selection_pay_integral_deduction)
//                            + rmbValue + mContext.getString(R.string.mall_selection_pay_yuan));
                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                            +" "+type+tokenAmount+" ");
                } else {
                    selectionPayMultipleBean.getSelectionPay().setPay(false);
                    selectionPayMultipleBean.getSelectionPay().setPayStatusHint(mContext.getString(R.string.mall_selection_pay_integral_hint)
                            +" "+type+tokenAmount+" "+" ("+mContext.getString(R.string.mall_selection_pay_balance_hint)+")");
                }
                //加载积分余额
                if (balanceData.contains(".")) {
                    selectionPayMultipleBean.getSelectionPay().setSurplusNum(balanceData);
                } else {
                    selectionPayMultipleBean.getSelectionPay().setSurplusNum(BalanceUtil.formatPrice(Double.valueOf(balanceData), true, 0));
                }

//            }
        }
        //更新当前item
        mallSelectionPayMultiAdapter.notifyDataSetChanged();

    }


    private void showPassDialog(final String tokenId, final String amount, final String orderIds) {
        PassWordAlertDialog dialog = new PassWordAlertDialog(mContext,
                new PassWordAlertDialog.OnEnterClick() {
                    @Override
                    public void passVerifySuccess(String passWord) {
//                        checkOutWithToken(tokenId,amount,orderIds);
                    }
                });
        dialog.setCanCancle(true);
        dialog.show();
    }

    //收款地址
    private String receiveAddress;
    /**
     * 付款地址
     */
//    private String payAddress = "0x29f7220c6f4eb0d40a2dc40b67787e7f7e51053a";

    private String payAddress = EnvironmentVariable.getProperty("tc_ethAddress", "");
    /**
     * 合约地址
     */
    private String contractAddress = "0x1fe7014f1aed0df06cd994388d64d276bcd37604";
    //转账金额
    private String amount = "10";
    //矿工费
    private String gasPrice1 = "0.0004";

    /**
     * 商品id
     */
    private String goodsId = "4";
    /**
     * 订单编号
     */
    private String orderNumber = "20181101103447856054";

    public void startTreasureTransfer(String orderNumber,String goodsId,String contractAddress,String gasPrice1,String amount,String quantity1){
        LoadingDataUtilBlack.show(mContext);
        TreasureTransferUtils.getInstance().startTreasureTransfer(mContext, payAddress, orderNumber
                , goodsId, contractAddress, gasPrice1,quantity1, amount, new EthTokenTransactionManager.TransactionCallBack() {
                    @Override
                    public void transactionResult(boolean isSuccess, Object result) {
                        LoadingDataUtilBlack.dismiss();
//                        LogUtils.e("夺宝交易---->"+(String)result);
                        if(isSuccess){
                            JSONObject jsonObject = JSONObject.fromObject(result);
                            if(jsonObject.getInt("code") == 0){
                                DialogUtil.showDialogNoCancel(mContext, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        view.paySuccess(null);
                                    }
                                },R.string.common_text_hint,mContext.getString(R.string.mall_win_treasure_pay_result_success_hint)
                                        ,mContext.getString(R.string.mail_sure));
                            }
                        }else {
                            ToastUtils.showShort(mContext.getString(R.string.mall_win_treasure_pay_result_fails_hint));
                        }

                    }
                });
    }

    /**
     * 根据商城商品编号来获取商品信息
     */
    public void getGoodsInfoById(final String goodsId){
        //http://treasure.openserver.cn/osp-treasure/winTreasure/getGoodsInfoById?goodsId=20181105
        String url = "http://treasure.openserver.cn/osp-treasure/winTreasure/getGoodsInfoById";
        LoadingDataUtilBlack.show(mContext);
        HashMap<String,String> map = new HashMap<>();
        map.put("goodsId",goodsId);
        MallRequestUtil.getRequest(TAG, url, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    MallTreasureGoodsInfoBean treasureGoodsInfoBean = gson.fromJson(response,MallTreasureGoodsInfoBean.class);
                    if(treasureGoodsInfoBean!=null){
                        if(treasureGoodsInfoBean.getCode() == 0){

                            //成功
                        }else {
                            //失败
                            ToastUtils.showShort(treasureGoodsInfoBean.getMsg());
                        }
                    }else {
                        ToastUtils.showShort(mContext.getString(R.string.mail_get_data_fail_again));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
            }
        });

    }
}
